package com.jing.ads.downloader;

import java.util.HashMap;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.widget.RemoteViews;

import com.jing.ads.R;
import com.jing.ads.application.GlobalConstants;
import com.jing.ads.util.StringUtil;

public class DownloadNotification implements Constants {
	private static final String NOTIFY_APP_PROGRESS = "com.jing.ads.notify.progress";

	private final Context mContext;
	// public final NotificationManager mNotificationMgr;
	// HashMap <String, NotificationItem> mNotificationItems;
	HashMap<Integer, Notification> mNotifications;

	static final String WHERE_RUNNING = "(" + Downloads.COLUMN_STATUS
			+ " >= '100') AND (" + Downloads.COLUMN_STATUS + " <= '199') AND ("
			+ Downloads.COLUMN_VISIBILITY + " IS NULL OR "
			+ Downloads.COLUMN_VISIBILITY + " == '"
			+ Downloads.VISIBILITY_VISIBLE + "' OR "
			+ Downloads.COLUMN_VISIBILITY + " == '"
			+ Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED + "')";
	static final String WHERE_COMPLETED = Downloads.COLUMN_STATUS
			+ " >= '200' AND " + Downloads.COLUMN_VISIBILITY + " == '"
			+ Downloads.VISIBILITY_VISIBLE_NOTIFY_COMPLETED + "'";

	/**
	 * This inner class is used to collate downloads that are owned by the same
	 * application. This is so that only one notification line item is used for
	 * all downloads of a given application.
	 * 
	 */
	static class NotificationItem {
		int id; // This first db _id for the download for the app
		int appId; // application id
		int totalCurrent = 0;
		int totalTotal = 0;
		int titleCount = 0;
		String appPackageName;// App package name
		String[] titles = new String[2]; // download titles.
		// int downloadType = -1;

		/*
		 * Add a second download to this notification item.
		 */
		void addItem(String title, int currentBytes, int totalBytes) {
			totalCurrent += currentBytes;
			if (totalBytes <= 0 || totalTotal == -1) {
				totalTotal = -1;
			} else {
				totalTotal += totalBytes;
			}
			if (titleCount < 2) {
				titles[titleCount] = title;
			}
			titleCount++;
		}
	}

	/**
	 * Constructor
	 * 
	 * @param ctx
	 *            The context to use to obtain access to the Notification
	 *            Service
	 */
	DownloadNotification(Context ctx) {
		mContext = ctx;
		// mNotificationMgr = (NotificationManager) mContext
		// .getSystemService(Context.NOTIFICATION_SERVICE);
		// mNotificationItems = new HashMap<String, NotificationItem>();
		mNotifications = new HashMap<Integer, Notification>();
	}

	/*
	 * Update the notification ui.
	 */
	public void updateNotification() {
		updateActiveNotification();
		updateCompletedNotification();
	}

	private void updateActiveNotification() {
		// Active downloads
		Cursor c = mContext.getContentResolver().query(
				Downloads.CONTENT_URI,
				new String[] { Downloads._ID, Downloads.COLUMN_APP_ID,
						Downloads.COLUMN_TITLE,
						Downloads.COLUMN_NOTIFICATION_EXTRAS,
						Downloads.COLUMN_CURRENT_BYTES,
						Downloads.COLUMN_TOTAL_BYTES, }, WHERE_RUNNING, null,
				Downloads._ID);

		if (c == null) {
			return;
		}

		// Columns match projection in query above
		final int idColumn = 0;
		final int appIdColumn = 1;
		final int titleColumn = 2;
		final int appPkgColumn = 3;
		final int currentBytesColumn = 4;
		final int totalBytesColumn = 5;
		// final int downloadTypeColumn = 6;

		// Collate the notifications
		// mNotificationItems.clear();
		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
			int max = c.getInt(totalBytesColumn);
			int progress = c.getInt(currentBytesColumn);
			// String title = c.getString(titleColumn);
			// if (title == null || title.length() == 0) {
			// title = mContext.getResources().getString(
			// R.string.status_download_unknown_title);
			// }
			// NotificationItem item = new NotificationItem();
			// item.id = c.getInt(idColumn);
			// item.appId = c.getInt(appIdColumn);
			String appPackageName = c.getString(appPkgColumn);
			// item.downloadType = c.getInt(downloadTypeColumn);
			// item.addItem(title, progress, max);
			// mNotificationItems.put(item.appPackageName, item);
			Intent i = new Intent(NOTIFY_APP_PROGRESS);
			i.putExtra("current", progress);
			i.putExtra("total", max);
			i.putExtra("pName", appPackageName);
			mContext.sendBroadcast(i);
		}
		c.close();

		// Add the notifications
		// for (NotificationItem item : mNotificationItems.values()) {

		// Build the notification object
		// Notification n;
		// if(mNotifications.containsKey(item.id)) {
		// n = mNotifications.get(item.id);
		// } else {
		// n = new Notification();
		// mNotifications.put(item.id, n);
		// }
		//
		// n.icon = android.R.drawable.stat_sys_download;
		//
		// n.flags |= Notification.FLAG_ONGOING_EVENT;
		//
		// RemoteViews expandedView = new RemoteViews(mContext.getPackageName(),
		// R.layout.notifity_layout);
		//
		// StringBuilder title = new StringBuilder(item.titles[0]);
		// // expandedView.setTextViewText(R.id.description,
		// // mContext.getString(R.string.downloading));
		// expandedView.setTextViewText(R.id.title, title);
		// expandedView.setProgressBar(R.id.progress_bar,
		// item.totalTotal,
		// item.totalCurrent,
		// item.totalTotal == -1);
		// expandedView.setTextViewText(R.id.description,
		// getDownloadingText(item.totalTotal, item.totalCurrent));
		// expandedView.setImageViewResource(R.id.appIcon,
		// android.R.drawable.stat_sys_download);
		// n.contentView = expandedView;

		// if(item.downloadType == GlobalConstants.TYPE_ID_DIRECT_DOWNLOAD) {
		// Intent intent = new Intent();
		// intent.setClassName(GlobalConstants.PACKAGE_NAME,
		// ActivityNativeDetail.class.getName());
		// intent.putExtra("appId", item.appId >= 0 ? item.appId : -1);
		// intent.putExtra("fromPage", "Notification");
		// intent.setData(Uri.parse("market://package/" +
		// item.appPackageName));//解决重复使用第一个intent，无实际功能用途
		// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		// n.contentIntent = PendingIntent.getActivity(mContext, 0, intent,
		// PendingIntent.FLAG_UPDATE_CURRENT);
		// }
		// mNotificationMgr.notify(item.id, n);
		// }
	}

	private void updateCompletedNotification() {
		// Completed downloads
		Cursor c = mContext.getContentResolver().query(Downloads.CONTENT_URI,
				new String[] { Downloads._ID, }, WHERE_COMPLETED, null,
				Downloads._ID);

		if (c == null) {
			return;
		}

		// Columns match projection in query above
		final int idColumn = 0;

		for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
			mNotifications.remove(c.getInt(idColumn));

			Uri contentUri = Uri.parse(Downloads.CONTENT_URI + "/"
					+ c.getInt(idColumn));
			ContentValues values = new ContentValues();
			values.put(Downloads.COLUMN_VISIBILITY,
					Downloads.VISIBILITY_VISIBLE);
			mContext.getContentResolver()
					.update(contentUri, values, null, null);
		}
		c.close();
	}

	private String getDownloadingText(long totalBytes, long currentBytes) {
		if (totalBytes <= 0) {
			return StringUtil.EMPTY_STRING;
		}

		long percent = 100L * currentBytes / totalBytes;
		return percent + "%";
	}
}
